<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-tabs v-model="activeTab" type="border-card">
			<el-tab-pane label="加班单详情" name="main">
				<el-card shadow="hover" class="layout-padding-auto create-form">
					<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>单据信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
										<template #label>
											<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.BillCode" class="width100" disabled></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_BillStatus_FormItem" prop="Entity.BillStatus">
										<template #label>
											<WtmLabelTooltip label="单据状态" tooltip="单据状态" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.BillStatus" class="width100" disabled>
											<el-option key="草稿" value="草稿" label="草稿"></el-option>
											<el-option key="正文" value="正文" label="正文"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_WorkflowStatus_FormItem" prop="Entity.WorkflowStatus">
										<template #label>
											<WtmLabelTooltip label="工作流状态" tooltip="工作流状态" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.WorkflowStatus" class="width100" disabled>
											<el-option key="待提交" value="待提交" label="待提交"></el-option>
											<el-option key="提交中" value="提交中" label="提交中"></el-option>
											<el-option key="审核中" value="审核中" label="审核中"></el-option>
											<el-option key="已完成" value="已完成" label="已完成"></el-option>
											<el-option key="已取消" value="已取消" label="已取消"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
										<template #label>
											<WtmLabelTooltip label="备注" tooltip="备注" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Remark" class="width100" disabled></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>基本信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_PersonId_FormItem" prop="Entity.PersonId">
										<template #label>
											<WtmLabelTooltip label="员工" tooltip="关联的员工实体" />
										</template>
										<WtmPersonSelector v-model="stateData.vmModel.Entity.PersonId" :disabled="true" :prefill-person="prefillPersonData" />
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
										<template #label>
											<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.StaffNo" class="width100" disabled></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
										<template #label>
											<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Name" class="width100" disabled></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>加班申请信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_RecordId_FormItem" prop="Entity.RecordId">
										<template #label>
											<WtmLabelTooltip label="加班记录" tooltip="选择关联的加班记录" />
										</template>
										<el-select
											v-model="stateData.vmModel.Entity.RecordId"
											clearable
											class="width100"
											placeholder="请选择加班记录"
											:loading="scheduleRecordsLoading"
											:disabled="true"
										>
											<el-option
												v-for="record in scheduleRecords"
												:key="record.ID"
												:value="record.ID"
												:label="`${record.ShiftDate} ${record.AttendanceShiftGroupName || '未知班次'}`"
											>
												<div>
													<span>{{ record.ShiftDate }}</span>
													<span style="margin-left: 10px; color: #8492a6">{{ record.AttendanceShiftGroupName || '未知班次' }}</span>
												</div>
											</el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_StartTime_FormItem" prop="Entity.StartTime">
										<template #label>
											<WtmLabelTooltip label="开始时间" tooltip="开始时间" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.StartTime" type="datetime" class="width100" disabled></el-date-picker>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_EndTime_FormItem" prop="Entity.EndTime">
										<template #label>
											<WtmLabelTooltip label="结束时间" tooltip="结束时间" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.EndTime" type="datetime" class="width100" disabled></el-date-picker>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_OvertimeHours_FormItem" prop="Entity.OvertimeHours">
										<template #label>
											<WtmLabelTooltip label="加班时长(小时)" tooltip="加班时长" />
										</template>
										<el-input-number v-model="stateData.vmModel.Entity.OvertimeHours" class="width100" disabled></el-input-number>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_CompensationType_FormItem" prop="Entity.CompensationType">
										<template #label>
											<WtmLabelTooltip label="加班补偿方式" tooltip="等时调休/薪资补助" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.CompensationType" class="width100" disabled>
											<el-option key="等时调休" value="等时调休" label="等时调休"></el-option>
											<el-option key="薪资补助" value="薪资补助" label="薪资补助"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20" v-if="stateData.vmModel.Entity.CompensationType === '等时调休'">
									<el-form-item ref="Entity_RemainingCompOffHours_FormItem" prop="Entity.RemainingCompOffHours">
										<template #label>
											<WtmLabelTooltip label="剩余调休时长" tooltip="等时调休剩余可用时长(小时)" />
										</template>
										<el-input-number v-model="stateData.vmModel.Entity.RemainingCompOffHours" class="width100" disabled></el-input-number>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Reason_FormItem" prop="Entity.Reason">
										<template #label>
											<WtmLabelTooltip label="加班事由" tooltip="加班事由" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Reason" type="textarea" :rows="2" class="width100" disabled></el-input>
									</el-form-item>
								</el-col>
							</el-row>

							<!-- 打卡记录 -->
							<div class="form-section" style="margin-top: 20px">
								<el-collapse v-model="activePunchCollapse" @change="handlePunchCollapseChange">
									<el-collapse-item name="punch">
										<template #title>
											<div style="display: flex; align-items: center; width: 100%">
												<i class="el-icon-time" style="margin-right: 8px"></i>
												<span style="font-weight: 500">打卡记录</span>
												<el-tag v-if="punchRecords.length > 0" type="info" size="small" style="margin-left: 10px">
													共 {{ punchRecords.length }} 条
												</el-tag>
											</div>
										</template>
										<div v-loading="punchLoading">
											<el-table :data="punchRecords" border stripe max-height="400" empty-text="暂无打卡记录">
												<el-table-column type="index" label="序号" width="60" align="center" />
												<el-table-column prop="StaffNo" label="工号" align="center" />
												<el-table-column prop="PunchTime" label="打卡时间" align="center">
													<template #default="scope">
														{{ formatDate(scope.row.PunchTime) }}
													</template>
												</el-table-column>
												<el-table-column prop="Location" label="打卡地点" show-overflow-tooltip />
											</el-table>
										</div>
									</el-collapse-item>
								</el-collapse>
							</div>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>工作信息</span>
							</div>
							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmOrgSelector v-model="stateData.vmModel.Entity.OrgId" label="公司" prop="Entity.OrgId" :auth="false" :disabled="true" />
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmDeptSelector v-model="stateData.vmModel.Entity.GroupId" prop="Entity.GroupId" label="所属部门" :auth="false" :disabled="true" />
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>审批信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Approver_FormItem" prop="Entity.Approver">
										<template #label>
											<WtmLabelTooltip label="审批人" tooltip="流程审批人" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Approver" class="width100" disabled></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_ApprovalTime_FormItem" prop="Entity.ApprovalTime">
										<template #label>
											<WtmLabelTooltip label="审批时间" tooltip="流程审批时间" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.ApprovalTime" type="datetime" class="width100" disabled></el-date-picker>
									</el-form-item>
								</el-col>
							</el-row>
						</div>
					</el-form>
				</el-card>
			</el-tab-pane>

			<el-tab-pane label="审批流程" name="workflow">
				<WtmWorkflowTimeline entityType="HengTong.Areas.Daily.Controllers.SysDailyOvertimeRequestBill" :entityId="stateData.vmModel.Entity.ID" />
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.details;false">
import { reactive, ref, computed, getCurrentInstance, onMounted, nextTick, type ComponentInternalInstance } from 'vue';
import { SysDailyOvertimeRequestBillApi as api } from '/@/views/daily/sysdailyovertimerequestbill/api';
import { SysAttendanceRawRecordApi } from '/@/views/hr/sysattendancerawrecord/api';

import other from '/@/utils/other';
import { ISysDailyOvertimeRequestBillVm } from '/@/views/daily/sysdailyovertimerequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import ApproveReasonDialog from '/@/components/approveReason/index.vue';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import { SysAttendanceRecordApi } from '/@/views/hr/sysattendancerecord/api';
import { ISearchByPersonRequest } from '/@/views/hr/sysattendancerecord/api/interface';

const ACTIONS = {
	AGREE: '同意',
	REJECT: '拒绝',
} as const;

const BUTTON_TEXTS = {
	AGREE: '同意',
	REJECT: '拒绝',
	CLOSE: '关闭',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const activeTab = ref('main');

// 打卡记录相关
const activePunchCollapse = ref<string[]>([]);
const punchLoading = ref(false);
const punchRecords = ref<any[]>([]);

// 排班记录相关
// 排班记录相关数据
const scheduleRecords = ref<any[]>([]);
const scheduleRecordsLoading = ref(false);
const attendanceRecordApi = SysAttendanceRecordApi();

const stateData = reactive<IViewModel<ISysDailyOvertimeRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null,
			PersonId: null,
			OrgId: null,
			StaffNo: null,
			Name: null,
			RecordId: null,
			StartTime: null,
			EndTime: null,
			OvertimeHours: null,
			CompensationType: null,
			RemainingCompOffHours: null,
			Reason: null,
			Approver: null,
			ApprovalTime: null,
			GroupId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
		} as any,
		ActionName: null,
		IsMyApprove: null,
		Remark: null,
	},
	AllSysGroups: [] as any[],
});

// 人员选择器预填充数据
const prefillPersonData = computed(() => {
	const entity = stateData.vmModel.Entity;
	if (entity.PersonId && entity.Name) {
		return {
			ID: entity.PersonId,
			Name: entity.Name,
			StaffNo: entity.StaffNo,
		};
	}
	return null;
});

const handleApiResponse = (response: any) => {
	loading.value = false;
	emit('refresh');
	closeDialog();
};

const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

const handleApproval = (actionName: string) => {
	stateData.vmModel.ActionName = actionName;
	loading.value = true;
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			api()
				.approve(stateData.vmModel, '')
				.then((res) => handleApiResponse(res))
				.catch(handleError);
		} else {
			loading.value = false;
		}
	});
};

const onAgree = () => {
	other.openDialog('填写同意原因', ApproveReasonDialog, null, null, '30%', (reason: string) => {
		stateData.vmModel.Remark = reason;
		handleApproval(ACTIONS.AGREE);
	});
};

const onDeny = () => {
	other.openDialog('填写拒绝原因', ApproveReasonDialog, { isRequired: true }, null, '30%', (reason: string) => {
		stateData.vmModel.Remark = reason;
		handleApproval(ACTIONS.REJECT);
	});
};

const onClose = () => {
	closeDialog();
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		(stateData.vmModel.Entity as any).ID = wtmdata.ID;
	}
};

// 加载排班记录
const loadScheduleRecords = async (personId: string) => {
	if (!personId) {
		scheduleRecords.value = [];
		return;
	}

	scheduleRecordsLoading.value = true;
	try {
		// 构建查询参数 - 查询当天前30天的排班记录
		const today = new Date();
		const startDate = new Date(today.getTime() - 60 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
		const endDate = today.toISOString().split('T')[0];

		const params: ISearchByPersonRequest = {
			PersonId: personId,
			Page: 1,
			Limit: 100,
			IsPlainText: true,
			IsEmunToString: true,
			ShiftDate: [startDate, endDate],
		};

		const response = await attendanceRecordApi.getSchedulingByPerson(params);

		// 过滤出已计算的考勤记录（排除"未计算"状态）
		let filteredRecords: any[] = [];
		if (response.Data && Array.isArray(response.Data) && (response.Data as any[]).length > 0) {
			const firstData = (response.Data as any[])[0];
			if (firstData && firstData.Records && Array.isArray(firstData.Records)) {
				filteredRecords = firstData.Records.filter((record: any) => {
					return record.ID && record.ShiftDate && record.AttendanceResult && record.AttendanceResult !== '未计算';
				});
			}
		}

		scheduleRecords.value = filteredRecords;
	} catch (error) {
		console.error('加载排班记录失败:', error);
		ElMessage.error('加载排班记录失败');
		scheduleRecords.value = [];
	} finally {
		scheduleRecordsLoading.value = false;
	}
};
// 加载页面数据（按照修改页面的逻辑）
const loadPageData = async () => {
	const API_ENDPOINTS = {
		GROUPS: '/api/SysDailyOvertimeRequestBill/GetSysGroups',
	} as const;

	const [groups, entityData] = await Promise.allSettled([
		other.getSelectList(API_ENDPOINTS.GROUPS, [], false),
		api().get(stateData.vmModel.Entity.ID ?? ''),
	]);

	// 处理成功的结果
	if (groups.status === 'fulfilled') stateData.AllSysGroups = groups.value;
	if (entityData.status === 'fulfilled') {
		other.setValue(stateData.vmModel, entityData.value);
		// 如果有人员ID，加载排班记录
		if (stateData.vmModel.Entity.PersonId) {
			await loadScheduleRecords(stateData.vmModel.Entity.PersonId);
			// 确保当前选中的排班记录在列表中
			await ensureCurrentRecordInList();
		}
	}
};

// 确保当前选中的排班记录在下拉列表中
const ensureCurrentRecordInList = async () => {
	const recordId = stateData.vmModel.Entity.RecordId;
	if (!recordId) return;

	// 检查当前记录是否已在列表中
	const existingRecord = scheduleRecords.value.find((record) => record.ID === recordId);
	if (existingRecord) return;

	// 如果不在列表中，尝试通过搜索接口获取这条记录（包含完整信息）
	try {
		const searchResponse: any = await attendanceRecordApi.search({
			PageIndex: 1,
			PageSize: 1,
			Searcher: { ID: recordId },
		});

		if (searchResponse && searchResponse.Data && searchResponse.Data.length > 0) {
			const record: any = searchResponse.Data[0];
			// 构建显示所需的字段
			const displayRecord = {
				ID: record.ID,
				ShiftDate: record.ShiftDate || '未知日期',
				AttendanceShiftGroupName: record.AttendanceShiftGroupName || record.AttendanceShift?.GroupName || record.AttendanceShift?.Name || '未知班次',
				AttendanceShift: record.AttendanceShift,
				AttendanceResult: record.AttendanceResult,
			};
			// 将记录添加到列表开头
			scheduleRecords.value.unshift(displayRecord);
		}
	} catch (error) {
		console.warn('获取选中的排班记录失败:', error);
		// 失败不影响页面显示，只是可能显示ID
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const canApprove = !!stateData.vmModel.IsMyApprove;

	const headerButtons = [
		{
			text: BUTTON_TEXTS.AGREE,
			type: 'primary',
			onClick: onAgree,
			visible: canApprove,
		},
		{
			text: BUTTON_TEXTS.REJECT,
			type: 'danger',
			onClick: onDeny,
			visible: canApprove,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};

// 格式化日期时间
const formatDate = (dateTime: any) => {
	if (!dateTime) return '';
	return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss');
};

// 折叠面板展开/收起时加载打卡记录
const handlePunchCollapseChange = async (activeNames: string | string[]) => {
	// 如果展开了打卡记录面板
	if (Array.isArray(activeNames) && activeNames.includes('punch')) {
		const staffNo = stateData.vmModel.Entity.StaffNo;

		if (!staffNo) {
			ElMessage.warning('员工工号不存在');
			activePunchCollapse.value = [];
			return;
		}

		punchLoading.value = true;
		punchRecords.value = [];

		try {
			// 检查开始时间和结束时间是否存在
			if (!stateData.vmModel.Entity.StartTime || !stateData.vmModel.Entity.EndTime) {
				ElMessage.warning('加班时间不完整');
				activePunchCollapse.value = [];
				return;
			}

			// 扩展时间范围：查询前后24小时的打卡记录
			// 使用 dayjs 进行日期计算，避免时区问题
			const startTime = dayjs(stateData.vmModel.Entity.StartTime);
			const endTime = dayjs(stateData.vmModel.Entity.EndTime);

			// 开始时间前24小时
			const searchStartTime = startTime.subtract(24, 'hour').format('YYYY-MM-DD HH:mm:ss');
			// 结束时间后24小时
			const searchEndTime = endTime.add(24, 'hour').format('YYYY-MM-DD HH:mm:ss');

			const response = await SysAttendanceRawRecordApi().search({
				StaffNo: staffNo,
				PunchTime: [searchStartTime, searchEndTime],
				PageIndex: 1,
				PageSize: 1000,
			});

			if (response.Data) {
				punchRecords.value = response.Data;
			}
		} catch (error: any) {
			ElMessage.error('查询打卡记录失败');
		} finally {
			punchLoading.value = false;
		}
	}
};
</script>
